package com.sunday.haowushop.ui.mine;

import android.content.Intent;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.StreamUtil;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.download.ImgUtils;
import com.sunday.haowushop.R;
import com.sunday.haowushop.common.AppConfig;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.http.ApiClient;
import com.sunday.haowushop.http.AppOperator;
import com.sunday.haowushop.ui.MainActivity;

import java.io.File;
import java.util.concurrent.Future;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/5/14.
 * 培训老师
 */

public class TeacherShareActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.imgView)
    ImageView imgView;
    @Bind(R.id.btn_select_pic)
    TextView btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_wechat_code);
        ButterKnife.bind(this);
        titleView.setText("我的培训老师");
        rightTxt.setVisibility(View.GONE);
        btn.setText("保存二维码到相册");
        initView();
        getData();
    }

    private void initView() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imgView.getLayoutParams();
        params.height = DeviceUtils.getDisplay(mContext).heightPixels * 3 / 5;
        imgView.setLayoutParams(params);
    }

    private String imgUrl;

    private void getData() {
        Call<ResultDO<String>> call = ApiClient.getApiAdapter().getRecCode(BaseApp.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO<String>>() {
            @Override
            public void onResponse(Call<ResultDO<String>> call, Response<ResultDO<String>> response) {
                if (isFinish) {
                    return;
                }
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    imgUrl = response.body().getResult();
                    if (response.body().getResult() != null) {
                        Glide.with(mContext)
                                .load(response.body().getResult())
                                .error(R.mipmap.ic_default)
                                .into(imgView);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO<String>> call, Throwable t) {

            }
        });
    }

    String filePath;

    @OnClick(R.id.btn_select_pic)
    void save() {
        if (TextUtils.isEmpty(imgUrl)) {
            return;
        }
        final Future<File> future = Glide.with(mContext)
                .load(imgUrl)
                .downloadOnly(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL);
        AppOperator.runOnThread(new Runnable() {
            @Override
            public void run() {
                try {
                    File sourceFile = future.get();
                    if (sourceFile == null || !sourceFile.exists())
                        return;
                    String extension = ImgUtils.getExtension(sourceFile.getAbsolutePath());
                    String extDir = AppConfig.DEFAULT_SAVE_IMAGE_PATH;
                    File extDirFile = new File(extDir);
                    if (!extDirFile.exists()) {
                        if (!extDirFile.mkdirs()) {
                            // If mk dir error
                            callSaveStatus(false, null);
                            return;
                        }
                    }
                    final File saveFile = new File(extDirFile, String.format("IMG_%1$s%2$s.%3$s", System.currentTimeMillis(), MD5Utils.random(), extension));
                    final boolean isSuccess = StreamUtil.copyFile(sourceFile, saveFile);
                    callSaveStatus(isSuccess, saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    callSaveStatus(false, null);
                }
            }
        });

    }


    private void callSaveStatus(final boolean success, final File savePath) {
        ((MainActivity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (success) {
                    // notify
                    Uri uri = Uri.fromFile(savePath);
                    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                    Log.i("img_name------", String.valueOf(savePath));
                    ToastUtils.showToast(mContext, "图片保存成功");
                } else {
                    ToastUtils.showToast(mContext, "图片保存失败");
                }
            }
        });
    }



}
